# -*- coding: utf-8 -*-
from lxml import etree
from rest import RestHTTP, HTTPConnectionException

class TableResourceManager(object):
    def __init__(self, baseurl):
        self.baseurl=baseurl
        self.conn = RestHTTP()

    def get_all(self):
        resp, content = self.conn.GET(self.baseurl)
        resptree=etree.fromstring(content)
        return resptree.xpath("/tables/table/@name")

    def get_table(self, tablename):
        resp, content = self.conn.GET("%s/%s" % (self.baseurl,tablename))
        return TableDef.from_xml(content)

    def create(self, tabledef):
        resp, content = self.conn.POST(self.baseurl, tabledef.__xml__(), expected_status=201)

    def delete(self, tablename):
        resp, content = self.conn.DELETE("%s/%s" % (self.baseurl,tablename), expected_status=204)

class FieldDef(object):
    def __init__(self, name, type, default=None, primarykey=False):
        self.name=name
        self.type=type
        self.default=default
        self.primarykey=primarykey

    def __xml__(self):
        field = etree.Element("field")
        field.set("name", self.name)
        field.set("type", self.type)

        if self.default:
            field.set("default",self.default)

        if self.primarykey:
            field.set("primarykey","true")

        return etree.tostring(field)

    def __cmp__(self, other):
        return self.name==other.name and self.type==other.type and self.default==other.default and self.primarykey==other.primarykey

class TableDef(object):
    def __init__(self, name):
        self.name=name
        self.fields={}

    def from_xml(cls, xml):
        tree=etree.fromstring(xml)
        table=TableDef(tree.xpath("/table/@name")[0])
        for field in tree.xpath("/table/field"):
            primarykey=field.attrib.get("primarykey",False)
            if primarykey=="true": primarykey=True
            table.add_field(field.attrib.get("name"), field.attrib.get("type"), primarykey=primarykey, default=field.attrib.get("default",None))
        return table
    from_xml = classmethod(from_xml)

    def add_field(self, name, type, default=None, primarykey=False):
        self.fields[name]=FieldDef(name,type,default,primarykey)

    def __xml__(self):
        table = etree.Element("table")
        table.set("name", self.name)
        table.set("created", "false")
        table.set("updated", "false")

        for field in self.fields.values():
            tree=etree.fromstring(field.__xml__())
            table.append(tree)

        return etree.tostring(table)

    def __cmp__(self, other):
        for name,field in self.fields.iteritems():
            if field!=other.fields[name]:
                return False
        return self.name==other.name
